<?php

namespace app\controller;

/***
 * 临时接口，暂时一通乱写。不考虑校验及其他规则，快速完成为主。
 */

use app\api\model\Collection;


use app\model\Storage,
    app\model\Location,
    app\model\Product,
    app\model\Order;

use think\Db;

class Api
{
    // 申请出库
    public function applyForOutbound()
    {

//        [["5ec100ce102a5","脂肪针","1","6.00","脂管加-丰泽","件"]]

        $params = array_trim(request()->post());
        $ids = explode(',', $params['ids']);
        $nums = explode(',', $params['nums']);

        $products = Db::name('product')
            ->alias('p')
            ->where('p.id', 'in', $ids)
            ->join('Storage s', 's.id= p.storage')
            ->join('Location l', 'l.id= p.location')
            ->field('p.*,s.name as storageName, l.name as locationName')
            ->select();

        $res = array();
        foreach ($products as $key => $value) {
            $tmpList = array($value['sn'], $value['name'], $nums[$key], $value['price'], $value['storageName'], $value['unit']);
            array_push($res, $tmpList);
        }

        $data['res'] = json_encode($res);
        $data['author'] = $params['author']; // '中医主任-陈xx';// 制单者（职务+名字
        $data['desc'] = $params['desc'];// 'xxx项目：减肥针1个，减肥药一包';// 项目描述

        $data['sn'] = 'SN' . date('YmdHis') . rand(10000, 99999); //这个要变成统一方法
        $data['supplier'] = '默认';
        $data['state'] = 2;
        $data['type'] = '项目出库';
        $data['add_time'] = time();
        $data['status'] = 1;

        $order = new Order();
        $order->data( $data );
        $order->save();

        return jsonReturn(1, 0, $data, '申请出库成功', 1);
    }

    // 仓库列表
    public function warehouses()
    {
        $list = Db::name('storage')->where(['status' => 0])->paginate()->each(function (&$item, $key) {
            $item['storage'] = Location::get(['storage' => $item['id']]);
            return $item;
        });
        return jsonReturn(1, 0, $list, '仓库列表', 1);
    }

    // 对应仓库下的商品列表
    public function products()
    {
        $params = array_trim(request()->get());
        $where['storage'] = $params['storage_id'];
        $where['location'] = $params['location_id'];
        $list = Db::name('product')->where($where)->select();
        return jsonReturn(1, 0, $list, '对应仓库下的商品列表', 1);
    }
}